#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "err.hpp"

namespace ns_server
{
    const uint16_t default_port = 8888;
    const int backlog = 32;
    using func_t = std::function<std::string(std::string)>;

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = default_port) : _port(port), _func(func)
        {
        }

        void InitServer()
        {
            // 1.创建套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                std::cerr << "create sock error," << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }

            std::cout << "create listensock success: " << _listensock << std::endl;

            // 2.绑定套接字
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind error," << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }

            // 3.监听
            if (listen(_listensock, backlog) < 0)
            {
                std::cerr << "listen error," << strerror(errno) << std::endl;
                exit(LISTEN_ERR);
            }
        }

        void service(int sock, std::string &clientIp, uint16_t clientPort)
        {
            std::string name = "[" + clientIp + ":" + std::to_string(clientPort) + "]";
            char buffer[1024];
            while (true)
            {
                int n = read(sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = '\0';
                    std::cout << name << "# " << buffer << std::endl;
                    std::string responce = _func(buffer);
                    int m = write(sock, responce.c_str(), responce.size());
                }
                else if (n == 0)
                {
                    // 写端关闭
                    std::cout << name << " quit,me to" << std::endl;
                    close(sock);
                    break;
                }
                else
                {
                    // 读数据异常
                    std::cerr << "read error" << std::endl;
                    break;
                }
            }
        }

        void Start()
        {
            signal(SIGCHLD,SIG_IGN);//忽略子进程的信号
            while (true)
            {
                struct sockaddr_in client;
                memset(&client, 0, sizeof(client));
                socklen_t len = sizeof(client);
                int sock = accept(_listensock, (struct sockaddr *)&client, &len);
                if (sock < 0)
                {
                    std::cerr << "accept error" << std::endl;
                    continue;
                }
                std::cout << "create sock " << sock << " from " << _listensock << std::endl;

                // 多进程
                pid_t id = fork();
                if (id < 0)
                {
                    close(sock);
                    continue;
                }
                else if (id == 0)
                {
                    //子进程
                    close(_listensock);//建议关掉不需要的fd
                    if(fork()>0)
                        exit(0);//子进程退掉，后续为孙子进程
                    // 提取客户端信息
                    std::string clientIp = inet_ntoa(client.sin_addr);
                    uint16_t clientPort = ntohs(client.sin_port);
                    service(sock, clientIp, clientPort);
                    exit(0);
                }
                close(sock);//一定关掉不需要的fd

                //pid_t ret=waitpid(id,nullptr,0);//默认为阻塞等待
                //pid_t ret=waitpid(id,nullptr,WNOHANG);//非阻塞
                //if(ret==id) std::cout<<"wait "<<id<<" sucess"<<std::endl;
            }
        }

        ~TcpServer()
        {
        }

    private:
        int _listensock; // 监听套接字
        uint16_t _port;  // 端口号
        func_t _func;    // 处理函数
    };
}